package com.ytkj.digitalConstruction.service.constructionprocess;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ytkj.digitalConstruction.dao.constructionprocess.NoticeParamMapper;
import com.ytkj.digitalConstruction.dao.constructionprocess.NoticeTempMapper;
import com.ytkj.digitalConstruction.entity.constructionprocess.NoticeParam;
import com.ytkj.digitalConstruction.entity.constructionprocess.NoticeTemp;
import com.ytkj.digitalConstruction.entity.message.Message;
import com.ytkj.digitalConstruction.entity.user.User;
import com.ytkj.digitalConstruction.enums.message.LinkMessagePicUrlEnum;
import com.ytkj.digitalConstruction.enums.message.MessageTypeEnum;
import com.ytkj.digitalConstruction.httpbean.constructionprocess.resbean.FlowProcessTemp;
import com.ytkj.digitalConstruction.httpbean.constructionprocess.resbean.WholeFlowInfo;
import com.ytkj.digitalConstruction.httpbean.message.reqbean.DingLink;
import com.ytkj.digitalConstruction.service.message.MessageService;
import com.ytkj.digitalConstruction.service.project.ProjectService;

@Service
@Transactional
public class SendNoticeService {

	private static final Logger log = LoggerFactory.getLogger(SendNoticeService.class);

	@Autowired
	private NoticeTempMapper noticeTempMapper;
	
	@Autowired
	private NoticeParamMapper noticeParamMapper;
	
	@Value("${dingding.url}")
	private String noticeHref;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private ProjectService projectService;
	
	/**
	 * @Description: 具体发送方法
	 * @Title: sendNotice 
	 * @param @param noticeTemp 
	 * @return void
	 * @throws
	 */
	public String sendNotice(NoticeTemp noticeTemp, User user, WholeFlowInfo flowInfo, Message message) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		FlowProcessTemp flowProcessTemp = ConstructionUtilService.getNowProcessBase(flowInfo.getFlowBaseInfo().getFlowProcesses());
		String dateStr = ConstructionUtilService.synthesisString(
				"[", dateFormat.format(new Date()), "] ", noticeTemp.getContent());
		if(noticeTemp.getId() == 6) {
			message.setTitle("风险教育文档");
		}else {
			message.setTitle(ConstructionUtilService.synthesisString(
					"[",flowInfo.getFlowBaseInfo().getFlowName(), "]进度更新至：",flowProcessTemp.getFlowName()));
		}
		message.setPublicDate(new Date());
		message.setType(MessageTypeEnum.DING.getValue());
		if(noticeTemp.getNoticeUrl() == null) {
			message.setMsgType("text");
			message.setContent(dateStr);
		}else {
			message.setMsgType("link");
			DingLink dingLink = new DingLink();
			dingLink.setPicUrl(LinkMessagePicUrlEnum.URL_ONE.getValue());
			dingLink.setTitle(message.getTitle());
			dingLink.setText(dateStr);
			dingLink.setMessageUrl(noticeHref.replace("[flowId]", flowInfo.getFlowBaseInfo().getFlowId().toString()));
			if("".equals(noticeTemp.getNoticeUrl())) {
				dingLink.setMessageUrl(dingLink.getMessageUrl().replace("[pageId]", flowProcessTemp.getFlowId().toString()));
			}else if(ConstructionUtilService.isNumber(noticeTemp.getNoticeUrl())){
				dingLink.setMessageUrl(dingLink.getMessageUrl().replace("[pageId]",noticeTemp.getNoticeUrl()));
			}else {
				dingLink.setMessageUrl(noticeTemp.getNoticeUrl());				
			}
			message.setContent(JSONObject.toJSONString(dingLink));
		}
		String userIds = null;
		try {
			List<Integer> roleIds = null;
			// 根据角色ids与项目id获取人员id集合
			roleIds = projectService.getUserIdListByprojectIdAndRoleIds(flowInfo.getFlowBaseInfo().getProjectId()
					, ConstructionUtilService.stringChangeIntegerList(noticeTemp.getNoticeReceiver()));
			if(roleIds.size() == 0) {
				return "";
			}
			userIds = roleIds==null?null:roleIds.toString().substring(1, roleIds.toString().length()-1).replace(" ", "");
			messageService.sendProcessMsg(message, userIds);
			
		} catch (Exception e) {
			log.error("\""+noticeTemp.getContent()+"\"消息发送异常，异常原因："+e);
		}
		return userIds;
	}
	
	/**
	 * @Description: 生成模板具体内容
	 * @Title: patchContent 
	 * @param @param noticeTemp
	 * @param @param noticeParams
	 * @return void
	 * @throws
	 */
	public void patchContent(NoticeTemp noticeTemp, List<NoticeParam> noticeParams) {
		if(noticeParams == null || noticeParams.size() == 0 || noticeTemp == null) {
			return;
		}
		for(NoticeParam noticeParam : noticeParams) {
			noticeTemp.setContent(noticeTemp.getContent()
					.replace(noticeParam.getVarCode(), noticeParam.getVarDemo()));
		}
		
	}
	
	/**
	 * @Description: 填充参数信息
	 * @Title: patchParam 
	 * @param @param noticeParams
	 * @param @param flowInfo 
	 * @return void
	 * @throws
	 */
	public void patchParam(List<NoticeParam> noticeParams, WholeFlowInfo flowInfo) {
		for(NoticeParam noticeParam : noticeParams) {
			patchParam(noticeParam, flowInfo);
		}
	}
	
	/**
	 * @Description: 填充参数信息
	 * @Title: patchParam 
	 * @param @param noticeParam
	 * @param @param flowInfo 
	 * @return void
	 * @throws
	 */
	public void patchParam(NoticeParam noticeParam, WholeFlowInfo flowInfo)	{
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		switch (noticeParam.getVarCode()) {
		case "【constructDeptName】":  // 施工方名称
			if(flowInfo.getFlowBaseInfo().getConstructDeptName() == null) {					
				break;
			}
			noticeParam.setVarDemo(flowInfo.getFlowBaseInfo().getConstructDeptName());
			break;
		case "【flowName】":  // 流程 名称
			if(flowInfo.getFlowBaseInfo().getFlowName() == null) {
				break;
			}
			noticeParam.setVarDemo(flowInfo.getFlowBaseInfo().getFlowName());
			break;
		case "【approachDate】":  // 进场时间
			if(flowInfo.getPreparation() == null || flowInfo.getPreparation().getApproachDate() == null) {
				break;
			}
			noticeParam.setVarDemo(dateFormat.format(flowInfo.getPreparation().getApproachDate()));
			break;
		case "【approachPath】":  // 进场路线
			if(flowInfo.getPreparation() == null || flowInfo.getPreparation().getApproachPath() == null) {
				break;
			}
			noticeParam.setVarDemo(flowInfo.getPreparation().getApproachPath());
			break;
		case "【eventRemark】":  // 停止原因
			if(flowInfo.getEvent() == null || flowInfo.getEvent().getEvent() == null) {
				break;
			}
			noticeParam.setVarDemo(flowInfo.getEvent().getEvent());
			break;
		case "【cancelRemark】":  // 无法施工原因
			if(flowInfo.getPlanInfoRes() == null || flowInfo.getPlanInfoRes().getRemark() == null) {
				break;
			}
			noticeParam.setVarDemo(flowInfo.getPlanInfoRes().getRemark());
			break;
		}
	}
	
	/**
	 * @Description: 按照typeId查询参数列表
	 * @Title: getNoticeParams 
	 * @param @param typeId
	 * @param @return 
	 * @return List<NoticeParam>
	 * @throws
	 */
	public List<NoticeParam> getNoticeParams(Integer typeId){
		return noticeParamMapper.selectByTypeId(typeId);
	}
	
	/**
	 * @Description: 按照typeId查询模板列表
	 * @Title: getNoticeTemp 
	 * @param @param typeId
	 * @param @return 
	 * @return List<NoticeTemp>
	 * @throws
	 */
	public List<NoticeTemp> getNoticeTemp(Integer typeId){
		return noticeTempMapper.selectByTypeId(typeId);
	}
	
	/**
	 * @Description: 发送流程
	 * @Title: sendFlow 
	 * @param @param typeId 消息发送的ID
	 * @param @param flowInfo
	 * @param @return 
	 * @return String
	 * @throws
	 */
	public String flowNoticeSend(Integer typeId, WholeFlowInfo flowInfo, User user) {
		List<NoticeParam> noticeParams = getNoticeParams(typeId);
		List<NoticeTemp> noticeTemps = getNoticeTemp(typeId);
		return patchContentAndSend(noticeParams, noticeTemps, flowInfo, user);
	}

	/**
	 * @Description: 制作文本并发送
	 * @Title: patchContentAndSend 
	 * @param @param noticeParams
	 * @param @param noticeTemps
	 * @param @param flowInfo
	 * @param @return 
	 * @return String
	 * @throws
	 */
	public String patchContentAndSend(List<NoticeParam> noticeParams, List<NoticeTemp> noticeTemps, WholeFlowInfo flowInfo, User user) {
		String userIds = null;
		patchParam(noticeParams, flowInfo);
		Message message = new Message();
		for(NoticeTemp noticeTemp : noticeTemps) {
			if(noticeTemp.getNoticeReceiver() == null || "".equals(noticeTemp.getNoticeReceiver())) {
				continue;
			}
			patchContent(noticeTemp, noticeParams);
			if(userIds == null) {
				userIds = sendNotice(noticeTemp, user, flowInfo, message);
			}else {
				sendNotice(noticeTemp, user, flowInfo, message);
			}
		}
		return userIds;
	}

	/**
	 * @Description: 获取需要的角色
	 * @Title: allNeedRoles 
	 * @param @return    设定文件 
	 * @return List<Integer>    返回类型 
	 * @throws
	 */
	public List<Integer> allNeedRoles(){
		String roles = noticeTempMapper.getAllNeedRoles();
		List<Integer> list = ConstructionUtilService.stringChangeIntegerList(roles);
		return new ArrayList<>(new HashSet<>(list));
	}
	
}
